from django.contrib.auth import login, authenticate, logout
from django.shortcuts import render
import json
# Create your views here.
from django.views import View
import logging
from demo.templates.views import login_required
from django.utils.decorators import method_decorator

# from goods.models import SKU
from goods.models import SKU

logger = logging.getLogger('django')
from users.models import User
from django.http import JsonResponse
import re
from django_redis import get_redis_connection


class UsernameCountView(View):

    def get(self, request, username):
        try:
            count = User.objects.filter(
                username=username
            ).count()
        except Exception as e:
            print(e)
            logger.error(e)
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'count': count
        })


class MobileCountView(View):
    def get(self, request, mobile):
        try:
            count = User.objects.filter(
                mobile=mobile
            ).count()
        except Exception as e:
            print(e)
            logger.error(e)
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'count': count
        })


class RegisterView(View):
    def post(self, request):
        data = json.loads(request.body.decode())
        username = data.get('username')
        password = data.get('password')
        password2 = data.get('password2')
        mobile = data.get('mobile')
        sms_code = data.get('sms_code')
        allow = data.get('allow')

        if not all([username, password, password2, mobile, sms_code]):
            return JsonResponse({'code': 400, 'errmsg': '缺少参数'}, status=400)
        if not re.match(r'^\w{5,20}$', username):
            return JsonResponse({'code': 400, 'errmsg': '用户名格式错误'}, status=400)
        if not re.match(r'^\w{8,20}$', password):
            return JsonResponse({'code': 400, 'errmsg': '密码格式错误'}, status=400)
        if password != password2:
            return JsonResponse({'code': 400, 'errmsg': '密码输入不一致'}, status=400)
        if not re.match(r'^\d{6}$', sms_code):
            return JsonResponse({'code': 400, 'errmsg': '验证码格式错误'}, status=400)
        if not allow:
            return JsonResponse({'code': 400, 'errmsg': '请求统一用户协议'}, status=400)
        conn = get_redis_connection('sms_code')
        sms_code_from_redis = conn.get('sms_%s' % mobile)
        if not sms_code_from_redis:
            return JsonResponse({'code': 400, 'errmsg': '短信验证码过期'}, status=400)
        sms_code_from_redis = sms_code_from_redis.decode()
        if sms_code_from_redis != sms_code:
            return JsonResponse({'code': 400, 'errmsg': '短信验证码错误'}, status=400)
        try:
            user = User.objects.create_user(
                username=username,
                password=password,
                mobile=mobile
            )
        except Exception as e:
            print(e)

        login(request, user)
        return JsonResponse({'code': 0, 'errmsg': 'OK'})


class LogoutView(View):
    def delete(self, request):
        logout(request)
        response = JsonResponse({'code': 0, 'errmsg': 'OK'})
        response.delete_cookie('username')
        return response


class LoginView(View):
    def post(self, request):

        data = json.loads(request.body.decode())
        username = data.get('username')
        password = data.get('password')
        remembered = data.get('remembered')
        if not all([username, password]):
            return JsonResponse({
                'code': 400,
                'errmsg': '缺少参数'
            })
        if not re.match(r'^\w{5,20}$', username):
            return JsonResponse({
                'code': 400,
                'errmsg': '账号输入错误'
            })
        if not re.match(r'^\w{8,20}$', password):
            return JsonResponse({
                'code': 400,
                'errmsg': '密码格式错误'
            })
        user = authenticate(request, username=username, password=password)
        if not user:
            return JsonResponse({'code': 400, 'errmsg': '账号或者密码输入错误'})
        login(request, user)
        if remembered:
            request.session.set_expiry(None)
        else:
            request.session.set_expiry(0)

        response = JsonResponse({'code': 0, 'errmsg': 'OK'})
        response.set_cookie('username', username, max_age=3600 * 24 * 14)
        return response


class UserInfoView(View):
    @method_decorator(login_required)
    def get(self, request):
        user = request.user

        return JsonResponse({
            'code': 0,
            'errmsg': 'OK',
            'info_data': {
                'username': user.username,
                'mobile': user.mobile,
                'email': user.email
            }
        })


from celery_tasks.email.tasks import send_verify_email


class EmailView(View):
    @method_decorator(login_required)
    def put(self, request):
        data = json.loads(request.body.decode())
        email = data.get('email')
        if not email:
            return JsonResponse({'code': 400, 'errmsg': '缺少参数'})
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({'code': 400, 'errmsg': '邮箱格式错误'})
        user = request.user
        try:
            user.email = email
            user.save()
        except Exception as e:
            print(e)
        verify_url = user.generate_verify_email_url()
        send_verify_email.delay(email, verify_url)
        return JsonResponse({'code': 0, 'errmsg': 'OK'})


class VerifyEmailView(View):
    def put(self, request):
        token = request.GET.get('token')
        user = User.check_verify_email_token(token)
        if not user:
            return JsonResponse({'code': 400, 'errmsg': '验证邮件无效'})
        user.email_active = True
        user.save()
        return JsonResponse({'code': 0, 'errmsg': '邮箱激活成功'})


from .models import Address


class CreateAddressView(View):
    def post(self, request):
        data = json.loads(request.body.decode())
        receiver = data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')
        user = request.user
        count = Address.objects.filter(user=user).count()
        if count >= 20:
            return JsonResponse({'code': 400, 'errmsg': '超过地址上限'})
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '缺少参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400, 'errmsg': '参数email有误'})
        try:
            address = Address.objects.create(
                user=user,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                title=receiver,
                place=place,
                mobile=mobile,
                tel=tel
            )
            if not user.default_address:
                user.default_address = address
                user.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '新增地址失败'})
        address_info = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        return JsonResponse({
            'code': 0,
            'errmsg': 'OK',
            'address': address_info
        })


class AddressView(View):
    def get(self, request):
        user = request.user
        addresses = Address.objects.filter(
            user=user,
            is_deleted=False
        )
        address_list = []
        for address in addresses:
            if address.id != user.default_address_id:
                address_list.append({
                    "id": address.id,
                    "title": address.title,
                    "receiver": address.receiver,
                    "province": address.province.name,
                    "city": address.city.name,
                    "district": address.district.name,
                    "place": address.place,
                    "mobile": address.mobile,
                    "tel": address.tel,
                    "email": address.email
                })
            else:
                address_list.insert(0, {
                    "id": address.id,
                    "title": address.title,
                    "receiver": address.receiver,
                    "province": address.province.name,
                    "city": address.city.name,
                    "district": address.district.name,
                    "place": address.place,
                    "mobile": address.mobile,
                    "tel": address.tel,
                    "email": address.email
                })
        return JsonResponse({
            'code': 0,
            'errmsg': 'OK',
            'default_address_id': user.default_address_id,
            'addresses': address_list
        })


class UpdateDestroyAddressView(View):
    def delete(self, request, address_id):
        try:
            address = Address.objects.get(pk=address_id)
        except Address.DoesNotExist as e:
            return JsonResponse({'code': 400, 'errmsg': '地址不存在'})
        address.is_deleted = True
        address.save()
        return JsonResponse({'code': 0, 'errmsg': 'OK'})

    def put(self, request, address_id):
        try:
            address = Address.objects.get(pk=address_id)
        except Address.DoesNotExist as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '更新失败'})
        data = json.loads(request.body.decode())
        receiver = data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '参数错误'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': 'mobile错误'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400, 'errmsg': 'tel错误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400, 'errmsg': 'email错误'})

        address.receiver = receiver
        address.province_id = province_id
        address.city_id = city_id
        address.district_id = district_id
        address.place = place
        address.mobile = mobile
        address.tel = tel
        address.email = email
        address.save()

        address_info = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email

        }
        return JsonResponse({
            'code': 0,
            'errmsg': 'OK',
            'address': address_info
        })


class DefaultAddressView(View):
    def put(self, request, address_id):
        user = request.user
        user.default_address_id = address_id
        user.save()
        return JsonResponse({'code': 0, 'errmsg': 'OK'})


class UpdateTitleAddressView(View):
    def put(self, request, address_id):
        data = json.loads(request.body.decode())
        title = data.get('title')
        address = Address.objects.get(pk=address_id)
        address.title = title
        address.save()
        return JsonResponse({
            'code': 0,
            'errmsg': 'OK'
        })


class ChangePasswordView(View):
    def put(self, request):
        data = json.loads(request.body.decode())
        old_password = data.get('old_password')
        new_password = data.get('new_password')
        new_password2 = data.get('new_password2')
        if not all([new_password2, new_password, old_password]):
            return JsonResponse({'code': 400, 'errmsg': '参数确实'})
        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return JsonResponse({'code': 400, 'errmsg': '密码格式错误'})
        if new_password != new_password2:
            return JsonResponse({'code': 400, 'errmsg': '两次密码输入不一致'})
        user = request.user

        if not user.check_password(old_password):
            return JsonResponse({'code': 400, 'errmsg': '旧密码输入不正确'}, status=400)
        user.set_password(new_password)
        user.save()  # 更新并保存修改后的密码
        logout(request)
        response = JsonResponse({'code': 0, 'errmsg': 'OK'})
        response.delete_cookie('username')
        return response


class UserBrowseHistory(View):
    @method_decorator(login_required)
    def post(self, request):
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        user = request.user
        conn = get_redis_connection('history')
        p = conn.pipeline()
        p.lrem('history_%s' % user.id, 0, sku_id)
        p.lpush('history_%s' % user.id, sku_id)
        p.ltrim('history_%s' % user.id, 0, 5)
        p.execute()
        return JsonResponse({'code': 0, 'errmsg': 'OK'})

    @method_decorator(login_required)
    def get(self, request):
        user = request.user
        conn = get_redis_connection('history')
        sku_ids = conn.lrange('history_%s' % user.id, 0, -1)
        skus = SKU.objects.filter(id__in=sku_ids)
        sku_list = []
        for sku in skus:
            sku_list.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image_url.url,
                'price': sku.price
            })
        return JsonResponse({
            'code': 0,
            'errmsg': 'OK',
            'skus': sku_list
        })
